<?php
defined('SYSPATH') or die('No direct access allowed.');
class Model_Zhilvyun_Api_Zhilvyun {

    private $secretId = 'AKIDekwdCbS7Lb3yqPEaUw5uqVYkagrgoCtMnd32';
    private $secretKey = 'f0t6chnuCxF7Yjfou5o29L5dqiD88P9pOivkcPzw';

//    private $url = 'http://www.v6.com/distribute/zhilvyun/api';
//    private $url = '';
    private $partnerId = '';

    private static $instance = null;


    public function  __construct($partnerId)
    {
        $this->partnerId = $partnerId;
        //$this->url = $this->env[$env];
    }


    public function request($data, $uri)
    {
        $header = $this->generateHeader($uri);
        //$data = json_encode($data);
        //请使用自己的curl工具
        $rtn = $this->http($uri, $data, $header);
        return $rtn;
    }

    /**
     * 生成header
     * @param $uri
     * @return array
     */
    public function generateHeader($uri)
    {
        date_default_timezone_set('GMT');
        $date = gmdate("D, d M Y H:i:s T");
        date_default_timezone_set('PRC');
        $authorization = $this->buildSign($uri,$date);
        $header = array(
            /*  'Host: '.$uri, // 用户 API 所在服务的域名
              'Accept: text/html',*/
            'Uri: '.$uri,
            'Date: '.$date,
            'Authorization: '.$authorization,
            //'X-Requested-With: XMLHttpRequest'
            //'Accept-Encoding: gzip, deflate, sdch'

        );
        return $header;

    }

    public function http($url,$data,$header)
    {

        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_POST, 'POST');
        curl_setopt($ch, CURLOPT_HTTPHEADER, $header);
        curl_setopt($ch, CURLOPT_POSTFIELDS,http_build_query($data));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST,FALSE);
        $rtn = curl_exec($ch);

        if (curl_errno($ch)) {
            print "Error: " . curl_error($ch);
        }
        curl_close($ch);
        if($this->isJson($rtn))
        {
            return json_decode($rtn,true);
        }
        else
        {
            return $rtn;
        }


    }

    //判断是否为json
    private function isJson($string)
    {
        json_decode($string);
        return (json_last_error() == JSON_ERROR_NONE);
    }

    public function outputError($res = '')
    {
        if(is_array($res))
        {
            $data = array_merge(array('code' => 300, 'secretId' => $this->secretId,), $res);
        }
        else
        {
            $data = array('code' => 300, 'msg' => $res, 'secretId' => $this->secretId);
        }

        exit(json_encode($data, JSON_UNESCAPED_UNICODE));
    }

    public function outputSuccess($res = array(), $desc = 'success')
    {
        $data = array_merge(
            array(
                'code' => 200,
                'msg' => $desc,
                'secretId' => $this->secretId
            ), $res);

        exit(json_encode($data, JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES));
    }

    public function validSign(){
        //todo sign 验证

        if($_SERVER['HTTP_AUTHORIZATION'] != self::buildSign( $_SERVER['REQUEST_URI'], $_SERVER['HTTP_DATE']))
        {
            self::outputError('BA验证错误');
        }
        return true;
    }

    //生成签名
    private function buildSign($uri,$date)
    {
        $srcStr = "date: ".$date."\n"."uri: ".$uri;
        $signStr = base64_encode(hash_hmac('sha1', $srcStr, $this->secretKey, true));
        $authorization = 'hmac id="'.$this->secretId.'", algorithm="hmac-sha1", headers="date uri", signature="';
        $authorization = $authorization.$signStr."\"";
        return $authorization;
    }

}